import React, { Component } from 'react';
import { View } from 'react-native';
import { commonMethods } from '../../utils';
import { Block } from './index';


class DetailPage extends Component {
  defaultProps = {
    uiData: [], // UI描述数据
    labelData: {}, // 右侧展示数据
    labelPrefix: '', // 右侧展示数据前缀
    dataUrl: '', // 右侧数据请求接口
    defaultFetchMethod: 'GET', // 右侧请求数据接口请求方式
    defaultParams: {}, // 右侧请求数据接口接口参数
  };

  labelData = {}

  uiData = []

  constructor(props) {
    super(props);
    this.state = {};
  }

  _initPage = () => {
    // 外界UI数据
    this.uiData = this.props.pageSetting.uiData || this.defaultProps.uiData;

    // 根据数据前缀解析指定位置的数据，不需要解析的话直接用
    if (this.props.pageSetting.labelPrefix) {
      this.labelData = commonMethods.getLabelByPathStr(
        this.props.pageSetting.labelPrefix,
        this.props.pageSetting.labelData,
      );
    } else {
      this.labelData = this.props.pageSetting.labelData;
    }

    // 优先使用已经传入的数据
    if (this.uiData && this.uiData.length > 0) {
      return this._parseDom(this.uiData, this.labelData); // 解析数据
    }
    // need todo
    // else{
    // fetch data by url
    // }
  }

  /**
   * 找到UI数据中key路径对应的值
  */
  _parseDom = (uiData) => {
    const list = [];
    let key = 0;
    uiData.forEach(element => {
      this._deepTraversal(element);
      if (element.type === 'block') {
        list.push(<Block data={element} key={key += 1} />);
      }
    });
    return list;
  }

  _deepTraversal = (obj) => {
    if (!obj) return;
    if (obj.contents && obj.contents.length) {
      obj.contents.map(item => this._deepTraversal(item));
    } else {
      obj.value = commonMethods.getLabelByPathStr(obj.key, this.labelData);
    }
  }

  render() {
    return (
      <View>
        {this._initPage()}
      </View>
    );
  }
}

export default DetailPage;
